import { request } from "@/service/request/index";
import { User } from "@/types/user";
import { getStore } from "@/store";

const getUserInfoByToken = async () => {
    try {
        return await request<User>("/user/profile", null);
    } catch (err) {
        throw err;
    }
};

export const login = async (account: string, password: string) => {
    try {
        const token = await request<string>("/user/login", {
            account: account,
            password: password,
        });
        sessionStorage.setItem("token", token);

        const userInfo = await getUserInfoByToken();
        getStore("user").setUserInfo(userInfo);
        getStore("user").setIsAuthenticated(true);
    } catch (err) {
        throw err;
    }
};

export const autoLogin = async () => {
    try {
        const userInfo = await getUserInfoByToken();
        getStore("user").setUserInfo(userInfo);
        getStore("user").setIsAuthenticated(true);
    } catch (err) {
        throw err;
    }
};
